package com.hzlx;


import com.hzlx.dto.CourseDto;
import com.hzlx.dto.CourseRequestDto;
import com.hzlx.dto.PageDto;

import com.hzlx.dto.ResultDto;
import jakarta.annotation.Resource;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


@RestController
public class CourseController {
    @Resource
    RestTemplate restTemplate;
    @PostMapping("/courses")
    public ResultDto<PageDto<CourseDto>> courses(CourseRequestDto requestDto){
        HttpHeaders headers = new HttpHeaders();
        //这是请求参数传递的方式为json
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<CourseRequestDto> entity = new HttpEntity<>(requestDto, headers);
        //响应数据类型
        ParameterizedTypeReference<ResultDto<PageDto<CourseDto>>> pt = new ParameterizedTypeReference<>() {};
        //远程调用
        ResponseEntity<ResultDto<PageDto<CourseDto>>> result =
                restTemplate.exchange("http://producer-demo/courses",
                        HttpMethod.POST,
                        entity,
                        pt);
        //将ResponseEntity中包裹的数据提出并返回
        return result.getBody();

     }
    @PostMapping("/coursesForm")
    public ResultDto<PageDto<CourseDto>> coursesForm(CourseRequestDto requestDto){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //表单参数
        MultiValueMap<String,Object> map = new LinkedMultiValueMap<>();
        map.add("account",requestDto.getAccount());
        map.add("page",requestDto.getPage());
        map.add("rows",requestDto.getRows());
        HttpEntity<MultiValueMap<String,Object>> entity = new HttpEntity<>(map,headers);
        ParameterizedTypeReference<ResultDto<PageDto<CourseDto>>> pt = new ParameterizedTypeReference<>() {};
        ResponseEntity<ResultDto<PageDto<CourseDto>>> result =
                restTemplate.exchange("http://producer-demo/coursesForm",HttpMethod.POST,entity,pt);
        return result.getBody();
    }
    @GetMapping("/courses/{account}/{page}/{rows}")
    public ResultDto<PageDto<CourseDto>> queryCourses(@PathVariable("account") String account,
                                                        @PathVariable("rows") Integer rows,
                                                        @PathVariable("page") Integer page)
    {
        ParameterizedTypeReference<ResultDto<PageDto<CourseDto>>> pt = new ParameterizedTypeReference<>() {};
        return  restTemplate.exchange("http://producer-demo/courses/{account}/{page}/{rows}",
                HttpMethod.GET,
                HttpEntity.EMPTY,
                pt,
                account,page,rows).getBody();
    }
}
